package com.rem.elasticsearch.apidemo.doc;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;
import java.util.HashMap;

import static org.apache.http.HttpHost.DEFAULT_SCHEME_NAME;

/**
 * 更新文档
 *
 * @author Rem
 * @date 2021-05-16
 */

@Slf4j
public class DocUpdate {


    public static void main(String[] args) throws IOException {
        // 创建ES客户端
        RestHighLevelClient esClient = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, DEFAULT_SCHEME_NAME))
        );
        // 修改文档 - 请求对象
        UpdateRequest request = new UpdateRequest();
        // 设置索引及唯一性标识
        request.index("user").id("2008");
        // 创建数据对象 map形式
        //request.doc(XContentType.JSON, "sex", "女");
        HashMap<String, Object> map = new HashMap<>();
        map.put("age", "20");

        //修改数据
        request.doc(map);
        // 客户端发送请求，获取响应对象
        UpdateResponse response = esClient.update(request, RequestOptions.DEFAULT);
        //3.打印结果信息
        System.out.println("_index:" + response.getIndex());
        System.out.println("_id:" + response.getId());
        System.out.println("_result:" + response.getResult());

        // 关闭ES客户端
        esClient.close();
    }
}
